<template>
  <div class="buyer-demand-page">
    <div class="demand-container">
      <div class="demand-form-section">
        <h2 class="section-title">发布种植需求</h2>
        
        <el-form 
          :model="demandForm" 
          :rules="demandRules" 
          ref="demandFormRef"
          label-width="120px"
          class="demand-form"
        >
          <!-- 农产品信息 -->
          <div class="form-section">
            <h3 class="section-subtitle">农产品信息</h3>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="农作物种类" prop="category">
                  <el-select v-model="demandForm.category" placeholder="选择种类">
                    <el-option label="蔬菜" value="vegetable" />
                    <el-option label="水果" value="fruit" />
                    <el-option label="谷物" value="grain" />
                    <el-option label="禽蛋" value="egg" />
                    <el-option label="其他" value="other" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="产品名称" prop="productName">
                  <el-input v-model="demandForm.productName" placeholder="例如：有机西红柿" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="需求数量" prop="quantity">
                  <el-input-number 
                    v-model="demandForm.quantity" 
                    :min="1" 
                    :max="1000"
                    placeholder="请输入数量"
                  />
                  <span class="unit">kg</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="期望单价" prop="unitPrice">
                  <el-input-number 
                    v-model="demandForm.unitPrice" 
                    :min="1" 
                    :precision="2"
                    placeholder="元/kg"
                  />
                  <span class="unit">元/kg</span>
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="产品要求" prop="requirements">
              <el-checkbox-group v-model="demandForm.requirements">
                <el-checkbox label="organic">有机种植</el-checkbox>
                <el-checkbox label="pesticideFree">无农药</el-checkbox>
                <el-checkbox label="nonGMO">非转基因</el-checkbox>
                <el-checkbox label="fresh">新鲜采摘</el-checkbox>
              </el-checkbox-group>
            </el-form-item>

            <el-form-item label="特殊要求" prop="specialRequirements">
              <el-input
                v-model="demandForm.specialRequirements"
                type="textarea"
                :rows="3"
                placeholder="请详细描述您对农产品的特殊要求（可选）"
                maxlength="500"
                show-word-limit
              />
            </el-form-item>
          </div>

          <!-- 交付信息 -->
          <div class="form-section">
            <h3 class="section-subtitle">交付信息</h3>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="期望交付时间" prop="expectedDeliveryTime">
                  <el-date-picker
                    v-model="demandForm.expectedDeliveryTime"
                    type="date"
                    placeholder="选择期望交付日期"
                    :disabled-date="disabledDate"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="收货人姓名" prop="recipientName">
                  <el-input v-model="demandForm.recipientName" placeholder="请输入收货人姓名" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="联系电话" prop="recipientPhone">
              <el-input v-model="demandForm.recipientPhone" placeholder="请输入联系电话" />
            </el-form-item>

            <el-form-item label="收货地址" prop="shippingAddress">
              <el-input
                v-model="demandForm.shippingAddress"
                type="textarea"
                :rows="2"
                placeholder="请输入详细收货地址"
              />
            </el-form-item>
          </div>

          <!-- 违约条款 -->
          <div class="form-section">
            <h3 class="section-subtitle">违约条款</h3>
            <div class="penalty-info">
              <p class="penalty-tip">
                💡 设置违约金可以激励农户按时完成订单，提高订单完成率
              </p>
            </div>
            <el-form-item label="违约金金额" prop="penaltyAmount">
              <el-input-number 
                v-model="demandForm.penaltyAmount" 
                :min="0" 
                :max="demandForm.totalAmount * 0.5"
                :precision="2"
                placeholder="设置违约金"
              />
              <span class="unit">元</span>
              <div class="penalty-tips">
                <p>建议违约金：订单总额的10%-30%</p>
                <p>当前订单总额：¥{{ totalAmount.toFixed(2) }}</p>
                <p v-if="demandForm.penaltyAmount > 0" class="penalty-warning">
                  如果农户违约，您将获得 ¥{{ demandForm.penaltyAmount.toFixed(2) }} 的违约金赔偿
                </p>
              </div>
            </el-form-item>
          </div>

          <!-- 订单总结 -->
          <div class="order-summary">
            <h3 class="summary-title">订单总结</h3>
            <div class="summary-content">
              <div class="summary-item">
                <span class="label">商品总额：</span>
                <span class="value">¥{{ totalAmount.toFixed(2) }}</span>
              </div>
              <div class="summary-item">
                <span class="label">预付定金：</span>
                <span class="value">¥{{ (totalAmount * 0.2).toFixed(2) }} (20%)</span>
              </div>
              <div class="summary-item" v-if="demandForm.penaltyAmount > 0">
                <span class="label">违约金：</span>
                <span class="value penalty">¥{{ demandForm.penaltyAmount.toFixed(2) }}</span>
              </div>
              <div class="summary-total">
                <span class="label">农户接单后预付：</span>
                <span class="value total">¥{{ (totalAmount * 0.2).toFixed(2) }}</span>
              </div>
            </div>
          </div>

          <!-- 提交按钮 -->
          <div class="form-actions">
            <el-button size="large" @click="resetForm">重置</el-button>
            <el-button 
              type="primary" 
              size="large" 
              @click="submitDemand"
              :loading="submitting"
            >
              发布种植需求 (预付 ¥{{ (totalAmount * 0.2).toFixed(2) }})
            </el-button>
          </div>
        </el-form>
      </div>

      <!-- 发布说明 -->
      <div class="instructions-section">
        <h3>发布说明</h3>
        <div class="instructions-content">
          <div class="instruction-item">
            <div class="icon">💰</div>
            <div class="content">
              <h4>预付定金</h4>
              <p>农户接单后，系统将自动扣除订单总额的20%作为预付定金支付给农户</p>
            </div>
          </div>
          <div class="instruction-item">
            <div class="icon">⏰</div>
            <div class="content">
              <h4>交付时间</h4>
              <p>请设置合理的交付时间，给农户足够的种植和准备时间</p>
            </div>
          </div>
          <div class="instruction-item">
            <div class="icon">⚖️</div>
            <div class="content">
              <h4>违约条款</h4>
              <p>设置适当的违约金可以保障您的权益，提高订单完成率</p>
            </div>
          </div>
          <div class="instruction-item">
            <div class="icon">🛡️</div>
            <div class="content">
              <h4>平台保障</h4>
              <p>平台会监督订单执行，确保双方权益得到保障</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'

const router = useRouter()

// 表单数据
const demandForm = ref({
  category: '',
  productName: '',
  quantity: 1,
  unitPrice: 0,
  requirements: [],
  specialRequirements: '',
  expectedDeliveryTime: '',
  recipientName: '',
  recipientPhone: '',
  shippingAddress: '',
  penaltyAmount: 0
})

const demandFormRef = ref(null)
const submitting = ref(false)

// 表单验证规则
const demandRules = {
  category: [
    { required: true, message: '请选择农作物种类', trigger: 'change' }
  ],
  productName: [
    { required: true, message: '请输入产品名称', trigger: 'blur' }
  ],
  quantity: [
    { required: true, message: '请输入需求数量', trigger: 'blur' },
    { type: 'number', min: 1, message: '数量至少为1kg', trigger: 'blur' }
  ],
  unitPrice: [
    { required: true, message: '请输入期望单价', trigger: 'blur' },
    { type: 'number', min: 1, message: '单价至少为1元', trigger: 'blur' }
  ],
  expectedDeliveryTime: [
    { required: true, message: '请选择期望交付时间', trigger: 'change' }
  ],
  recipientName: [
    { required: true, message: '请输入收货人姓名', trigger: 'blur' }
  ],
  recipientPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  shippingAddress: [
    { required: true, message: '请输入收货地址', trigger: 'blur' }
  ]
}

// 计算属性
const totalAmount = computed(() => {
  return demandForm.value.quantity * demandForm.value.unitPrice
})


// 方法
const disabledDate = (time) => {
  // 只能选择今天之后的日期
  return time.getTime() < Date.now() - 8.64e7
}

const resetForm = () => {
  demandFormRef.value?.resetFields()
  demandForm.value.penaltyAmount = 0
  demandForm.value.requirements = []
  demandForm.value.specialRequirements = ''
}

const submitDemand = async () => {
  if (!demandFormRef.value) return

  try {
    const valid = await demandFormRef.value.validate()
    if (!valid) return

    submitting.value = true

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 2000))

    // 创建订单
    const orderData = {
      id: Date.now(),
      orderNumber: `DM${Date.now()}`,
      ...demandForm.value,
      totalAmount: totalAmount.value,
      status: 'pending',
      createTime: new Date().toISOString(),
      advancePayment: totalAmount.value * 0.2
    }

    console.log('发布需求订单:', orderData)
    
    ElMessage.success('需求订单发布成功！等待农户接单')
    
    // 跳转到订单页面
    router.push('/buyer/orders')
    
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitting.value = false
  }
}

</script>

<style scoped>
.buyer-demand-page {
  min-height: 100vh;
  background-color: #f5f7fa;
  font-family: 'Inter', 'PingFang SC', 'Microsoft YaHei', sans-serif;
}

.demand-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 30px 20px;
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 30px;
  
}

.demand-form-section {
  background: white;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.section-title {
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 30px;
  text-align: center;
}

.section-subtitle {
  font-size: 18px;
  font-weight: 600;
  color: #374151;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 2px solid #e5e7eb;
}

.form-section {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e5e7eb;
}

.form-section:last-of-type {
  border-bottom: none;
}

.unit {
  margin-left: 8px;
  color: #6b7280;
  font-size: 14px;
}

.penalty-info {
  background: #f0f9ff;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 16px;
}

.penalty-tip {
  margin: 0;
  color: #0369a1;
  font-size: 14px;
}

.penalty-tips {
  margin-top: 8px;
  font-size: 12px;
  color: #6b7280;
}

.penalty-tips p {
  margin: 4px 0;
}

.penalty-warning {
  color: #dc2626;
  font-weight: 500;
}

.order-summary {
  background: #f8fafc;
  border-radius: 8px;
  padding: 20px;
  margin: 30px 0;
}

.summary-title {
  font-size: 16px;
  font-weight: 600;
  color: #374151;
  margin-bottom: 16px;
}

.summary-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.summary-item .label {
  color: #6b7280;
}

.summary-item .value {
  color: #1f2937;
  font-weight: 500;
}

.summary-item .value.penalty {
  color: #dc2626;
}

.summary-total {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 12px;
  border-top: 1px solid #e5e7eb;
  margin-top: 8px;
}

.summary-total .label {
  color: #1f2937;
  font-weight: 600;
}

.summary-total .value.total {
  color: #ef4444;
  font-size: 18px;
  font-weight: 700;
}

.form-actions {
  display: flex;
  gap: 16px;
  justify-content: center;
  margin-top: 30px;
}

.instructions-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  height: fit-content;
  position: sticky;
  top: 30px;
}

.instructions-section h3 {
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 20px;
  text-align: center;
}

.instructions-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.instruction-item {
  display: flex;
  gap: 12px;
  padding: 16px;
  background: #f8fafc;
  border-radius: 8px;
}

.instruction-item .icon {
  font-size: 24px;
  flex-shrink: 0;
}

.instruction-item .content h4 {
  margin: 0 0 8px 0;
  color: #1f2937;
  font-size: 14px;
  font-weight: 600;
}

.instruction-item .content p {
  margin: 0;
  color: #6b7280;
  font-size: 13px;
  line-height: 1.4;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .demand-container {
    grid-template-columns: 1fr;
  }
  
  .header-container {
    flex-direction: column;
    gap: 16px;
  }
  
  .demand-form-section {
    padding: 20px;
  }
  
  .form-actions {
    flex-direction: column;
  }
  
  .instruction-item {
    flex-direction: column;
    text-align: center;
  }
}
</style>